package com.polaris.live.ui.live.proxy.gift

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.polaris.live.common.ext.dp
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.im.sfs.bean.live.payload.InviteGiftPayloadBean
import com.polaris.live.utils.image.ImageUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 通话页面的礼物动画代理类
 */
class CallGiftAnimationProxy(
    private val context: Context,
    private val llGift: LinearLayout,
    private val owner: LifecycleOwner,
    private val viewModel: BaseViewModel
) {

    //等待的礼物队列
    private val giftWaitList = ConcurrentLinkedQueue<SendLiveMessage>()

    //当前是否有动画展示中
    private var isRunning = AtomicBoolean(false)

    //当前展示的礼物的view
    private var view: View? = null

    //进场动画
    private var inAnim: ObjectAnimator? = null

    //缩放动画
    private var scaleAnimator: ObjectAnimator? = null

    //离开动画
    private var alphaAnimator: ObjectAnimator? = null

    init {
        owner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                when (event) {
                    Lifecycle.Event.ON_STOP -> {
                        //停止各种各样的东西
                        inAnim?.cancel()
                        scaleAnimator?.cancel()
                        alphaAnimator?.cancel()
                        inAnim = null
                        scaleAnimator = null
                        alphaAnimator = null
                    }

                    else -> {}
                }
            }
        })
    }

    /**
     * 添加礼物逻辑
     */
    fun addGift(sendLiveMessage: SendLiveMessage) {
        val payload = sendLiveMessage.payload as InviteGiftPayloadBean
        if (isRunning.get() || !giftWaitList.isEmpty()) {
            addQueue(payload.giftCount, sendLiveMessage)
        } else {
            isRunning.set(true)
            if (payload.giftCount > 1) {
                addQueue(payload.giftCount - 1, sendLiveMessage)
            }
            showGift(sendLiveMessage)
        }
    }

    private fun showGift(sendLiveMessage: SendLiveMessage) {
        val payload = sendLiveMessage.payload as InviteGiftPayloadBean
        addImageView(payload.gift.pic)
        riseAnimation()
    }

    private fun addQueue(count: Int, sendLiveMessage: SendLiveMessage) {
        for (i in 0 until count) {
            giftWaitList.add(sendLiveMessage)
        }
    }

    //添加view
    private fun addImageView(pic: String) {
        val image = ImageView(context)
        val imageLayoutParams = LinearLayout.LayoutParams(
            56.dp,
            56.dp
        )
        image.layoutParams = imageLayoutParams
        image.scaleType = ImageView.ScaleType.FIT_XY
        Glide.with(image.context)
            .load(ImageUtils.imgPath(pic))
            .into(image)

        view = image

        llGift.addView(image)
    }

    /**
     * 礼物进入动画
     */
    @SuppressLint("ObjectAnimatorBinding")
    private fun riseAnimation() {
        val height = ScreenUtils.getScreenHeight() / 3
        inAnim = ObjectAnimator.ofFloat(view, "translationY", 0f, -height.toFloat())
            .apply {
                interpolator = AccelerateInterpolator()
                duration = 650
                addListener(object : Animator.AnimatorListener {
                    override fun onAnimationStart(animation: Animator) {}
                    override fun onAnimationEnd(animation: Animator) {
                        // 动画结束时的操作
                        scaleAnimation()
                    }

                    override fun onAnimationCancel(animation: Animator) {}
                    override fun onAnimationRepeat(animation: Animator) {}
                })
                start()
            }

    }

    /**
     * 缩放动画
     */
    @SuppressLint("ObjectAnimatorBinding")
    private fun scaleAnimation() {
        scaleAnimator = ObjectAnimator.ofPropertyValuesHolder(
            view,
            PropertyValuesHolder.ofFloat("scaleX", 1.0f, 3f),
            PropertyValuesHolder.ofFloat("scaleY", 1.0f, 3f)
        )
            .apply {
                interpolator = LinearInterpolator()
                duration = 1000
                start()
                addListener(object : AnimatorListenerAdapter() {

                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        viewModel.viewModelScope.launch {
                            delay(1000)
                            withContext(CoroutineScopeManager.mainDispatcher) {
                                endAnimation()
                            }
                        }
                    }
                })
            }
    }

    /**
     * 结束动画
     */
    @SuppressLint("ObjectAnimatorBinding")
    private fun endAnimation() {
        alphaAnimator = ObjectAnimator.ofFloat(view, "alpha", 1.0f, 0.0f)
            .apply {
                interpolator = LinearInterpolator()
                duration = 400
                start()
                addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        view?.visibility = View.GONE
                        llGift.post {
                            llGift.removeAllViews()
                        }
                        this@CallGiftAnimationProxy.isRunning.set(false)
                        giftWaitList.poll()?.let { showGift(it) }
                    }
                })
            }
    }
}